package data_store

import "sync"

type NameItem struct {
	ServiceName  string
	RootSpanName string
}

type NameTable struct {
	nameMap map[NameItem]bool
	mutex   sync.Mutex
}

func newNameTable() *NameTable {
	return &NameTable{
		nameMap: map[NameItem]bool{},
	}
}

func (tab *NameTable) Insert(nameItem NameItem) {
	tab.mutex.Lock()
	defer tab.mutex.Unlock()

	if nameItem.ServiceName == "" || nameItem.RootSpanName == "" {
		return
	}

	tab.nameMap[nameItem] = true
}

func (tab *NameTable) ListServiceName() []string {
	tab.mutex.Lock()
	defer tab.mutex.Unlock()

	tmpMap := map[string]bool{}

	for k, _ := range tab.nameMap {
		tmpMap[k.ServiceName] = true
	}

	retList := []string{}
	for k, _ := range tmpMap {
		retList = append(retList, k)
	}
	return retList
}

func (tab *NameTable) ListRootSpanName(filterByServiceName bool, serviceName string) []string {
	tab.mutex.Lock()
	defer tab.mutex.Unlock()

	tmpMap := map[string]bool{}

	for k, _ := range tab.nameMap {
		if filterByServiceName && k.ServiceName != serviceName {
			continue
		}
		tmpMap[k.RootSpanName] = true
	}

	retList := []string{}
	for k, _ := range tmpMap {
		retList = append(retList, k)
	}
	return retList
}
